﻿using JWT;
using JWT.Algorithms;
using JWT.Exceptions;
using JWT.Serializers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AppFlat.Common.Jwt
{
    public class JwtHelper
    {
        //HMACSHA256加密
        static IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
        //序列化和反序列
        static IJsonSerializer serializer = new JsonNetSerializer();
        //Base64编解码
        static IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
        //UTC时间获取
        static IDateTimeProvider provider = new UtcDateTimeProvider();
        const string secret = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQK";//服务端

        public static string JiaM(Dictionary<string,object> payload)
        {   //设置过期时间(可以不设置，下面表示签名后 20分钟过期)         
            double exp = (DateTime.UtcNow.AddMinutes(20) - new DateTime(1970, 1, 1)).TotalSeconds;

            //注意这个是额外的参数，默认参数是 typ 和alg         
            var headers = new Dictionary<string, object>();
            //{
            //    { "typ","JWT" },
            //    {"alg","HS256" }
            //};
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            var token = encoder.Encode(headers, payload, secret);
            return token;
        }
        public static string JieM(string token)
        {
            try
            {
                //用于验证JWT的类
                IJwtValidator validator = new JwtValidator(serializer, provider);
                //用于解析JWT的类            
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
               // IJwtDecoder decoder = new JwtDecoder(serializer, urlEncoder);
                var json = decoder.Decode(token, secret, true);
                return json;
            }
            catch (TokenExpiredException e)
            {
                //过期了自动进入这里             
                return "Token has expired";
            }
            catch (SignatureVerificationException e)
            {
                //校验未通过自动进入这里             
                return "Token has invalid signature";
            }
            catch (Exception e)
            {
                //其它错误，自动进入到这里             
                return "other error";
            }

        }
    }
}
